<template>
  <view :class="ns.b()" :ref='editorRef'> <switch :checked="currentVal" @change="handleChange" /></view>
</template>
<script lang="ts">
export default {
  options: {
    addGlobalClass: true,
    virtualHost: true,
    styleIsolation: "shared"
  }
}
</script>
<script lang="ts" setup>
  import { getSwitchProps } from "@/props";
  import { SwitchEditorController } from "./i-biz-switch.controller";
  import { useFocusAndBlur, useNamespace } from "@/use";
  import { ref, watch } from "vue";

  const props = defineProps(getSwitchProps<SwitchEditorController>());
  const emit = defineEmits();
  const ns = useNamespace("switch");
  const currentVal = ref<boolean>(false);

  watch(
    () => props.value,
    (newVal, oldVal) => {
      if (newVal !== oldVal) {
        if (!newVal) {
          currentVal.value = false;
        } else {
          // eslint-disable-next-line eqeqeq
          currentVal.value = props.value == 1;
        }
      }
    },
    { immediate: true }
  );

  const handleChange = (event: IData) => {
    const value = event.detail.value;
    console.log("开关：", event);
    const emitValue = value === true ? 1 : 0;
    emit("change", emitValue);
  };

  // 聚焦失焦事件
  const { componentRef: editorRef } = useFocusAndBlur(
    () => emit("focus"),
    () => emit("blur")
  );
</script>
